package com.numbfish.mapper;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.BeforeClass;

import java.io.IOException;
import java.io.Reader;
import java.util.function.Consumer;

/**
 * 初始化SqlSessionFactory  SqlSession 公共代码抽取
 */

public abstract class BaseMapper {
    protected static SqlSessionFactory sqlSessionFactory;
    @BeforeClass
    public static void init(){
        try {
            Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
            reader.close();
        } catch (IOException ignore) {
            ignore.printStackTrace();
        }
    }

    protected void executeQuery(Consumer<SqlSession> consumer){
        SqlSession sqlSession = sqlSessionFactory.openSession();
        try {
            consumer.accept(sqlSession);
        } finally {
            sqlSession.close();
        }
    }

    protected void executeThenRollback(Consumer<SqlSession> consumer){
        SqlSession sqlSession = sqlSessionFactory.openSession();
        try {
            consumer.accept(sqlSession);
        } finally {
            // sqlSession 不是自动提交的
            sqlSession.rollback();
            sqlSession.close();
        }
    }

}
